from flask import Blueprint,request,make_response,redirect,jsonify
from application.models.users.user import User,db,SfLogin
from utils.captcha.captcha import captcha
from utils.myredis import r
import redis
from utils.myjwt import myjwt

sf_blue = Blueprint("sfbule",__name__)

@sf_blue.route("/sflogin")
def sflogin():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code":200,"url":url})


import requests
import json
import time
# 回调接口
@sf_blue.route("/user/weiboCallback/")
def Callback():
    code=request.args.get("code")
    # 向access_token接口发起post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    mes=json.loads(res.text)
    token=mes['access_token']
    uid=mes['uid']
    # 查询三方登录中uid是否存在，如果存在，查询用户表，用用户信息生成token跳转到vue页面
    sql = "select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'" % (
        str(uid))
    user=db.session.execute(sql)
    if user:
        for i in user:
            data={"data":{"userid":i[0],"exp":int(time.time())}}
            token=myjwt.jwt_encode(data)
            return redirect("http://localhost:8080/#/?userid="+str(i[0])+"&token="+token)

    return redirect("http://localhost:8080/#/wbzz?uid="+str(uid)+"&token="+token)


# 绑定用户的接口
@sf_blue.route("/bindMobile",methods=['POST'])
def bindMobile():
    data=json.loads(request.data)
    mobile=data['mobile']
    uid=data['uid']
    token=data['token']
    # 先查询用户表，如果手机号存在
    user=User.query.filter(User.mobile== mobile).first()
    if not user:
        # 添加用户 如果不存在写入用户表
        u=User(mobile=mobile,nikename=mobile)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user=User.query.filter(User.mobile == mobile).first()
    sfuser=SfLogin(userid=user.id,webfrom='wb',uid=uid,token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 获取userid写入三方登录表。生成token返回
    data={"data":user.id,"exp":int(time.time())}
    token=myjwt.jwt_encode(data)
    return jsonify({"userid":str(user.id),"token":token})




